/**
 * 
 */
package iut2.sponsor.client;

import java.util.HashMap;

import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.drop.GridConstrainedDropController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author wolfer
 *
 */
public class FlyerDropController extends GridConstrainedDropController {

	private final GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
	
	private HashMap<Widget, SponsorArgent> widgets;
	private int gridX;
	private int gridY;
	private int colonne;
	
	public FlyerDropController(AbsolutePanel dropTarget, int gridX, int gridY,
			HashMap<Widget, SponsorArgent> widgets, int colonne) {
		super(dropTarget, gridX, gridY);
		this.gridX = gridX;
		this.gridY = gridY;
		this.widgets = widgets;
		this.colonne = colonne;
	}

	@Override
	/**
	 * 
	 * onDrop event
	 * @param context ...
	 */
	public void onDrop(DragContext context) {
		super.onDrop(context);
		
		int x = (context.draggable.getAbsoluteLeft() - super.getDropTarget().getAbsoluteLeft()) / gridX;
		int y = (context.draggable.getAbsoluteTop() - super.getDropTarget().getAbsoluteTop()) / gridX;
		
		for (Widget w: widgets.keySet()) {
			int xw = (w.getAbsoluteLeft() - super.getDropTarget().getAbsoluteLeft()) / gridX;
			int yw = (w.getAbsoluteTop() - super.getDropTarget().getAbsoluteTop()) / gridX;

			if (!w.equals(context.draggable) && (xw == x) && (yw == y)) {
				int pox = (widgets.get(context.draggable).getEmplacement()%colonne)*gridX;
				int poy = (int)(widgets.get(context.draggable).getEmplacement()/colonne)*gridY;
				
				drop(w, pox, poy);
				widgets.get(w).setEmplacement(widgets.get(context.draggable).getEmplacement());
			}
		}
		widgets.get(context.draggable).setEmplacement(x + (y*colonne));
		updateServerList();
	}
	
	/**
	 * Update sponsor list on server
	 */
	private void updateServerList() {
		AsyncCallback<Integer> myMethodCallback = new AsyncCallback<Integer>() {
			public void onSuccess(Integer result) {
			}

			public void onFailure(Throwable ex) {
				RootPanel.get().add(new HTML(ex.toString()));
			}
		};

		// Effectuer l'appel au service
		greetingService.updateSponsors(Iut2sponsor.SINGLETON.getSponsors(), myMethodCallback);
	}
}
